package com.junmo.oauth.module.system.controller;


import com.junmo.oauth.module.system.entity.SysUser;
import com.junmo.oauth.module.system.service.SysUserService;
import com.junmo.oauth.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
@Slf4j
public class SysUserController {
    @Autowired
    SysUserService sysUserService;

    //int page, int size
    @GetMapping("/page")
    public R page(SysUser search, Integer currentPage, Integer pageSize,
                  @RequestParam(defaultValue = "username") String sortField, @RequestParam(defaultValue = "asc")String sortOrder){
        Sort.Direction direction= sortOrder.toLowerCase().contains("asc")?Sort.Direction.ASC:Sort.Direction.DESC;
        Pageable pageable = PageRequest.of(currentPage - 1, pageSize,Sort.by(direction,sortField));
        Page<SysUser> page =  sysUserService.page( search, pageable);
        return R.success(page);
    }

    @PostMapping()
    public R create(@RequestBody  SysUser entity){
        return  sysUserService.create( entity);
    }

    @PutMapping()
    public R edit(@RequestBody  SysUser entity){
        return  sysUserService.edit( entity);
    }

    @DeleteMapping()
    public R deleteByIds(@RequestBody List<Number> ids){
        return  sysUserService.deleteByIds( ids);
    }
    @PostMapping("/assignRole/{userId}")
    public R assignRole(@PathVariable("userId") Number userId ,@RequestBody List<Number> roleIds){
        return  sysUserService.assignRole( userId,roleIds);
    }
}
